<template>
  <div class="user-list">
    <div class="title">用户列表</div>
    <el-form :inline="true" class="search-form">
      <el-col :span="19">
        <el-form-item>
          <el-input
            v-model="searchName"
            placeholder="输入姓名/账号"
            clearable
            @keyup.enter.native="queryUserList('search')">
            <template #append>
              <el-button icon="el-icon-search" @click="queryUserList('search')" />
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" class="button-container" size="14" @click="handleAdd">新增用户</el-button>
      </el-col>
    </el-form>

    <el-table
      v-loading="loading"
      :data="tableUserData"
      style="width: 100%"
      size="medium"
      :header-cell-style="{ background: '#F5F6F7' }">
      <el-table-column label="账号">
        <template slot-scope="scope">
          {{ scope.row.username || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="姓名">
        <template slot-scope="scope">
          {{ scope.row.name || "-" }}
        </template>
      </el-table-column>
      <el-table-column v-if="rolesCode !== 'PLATFORM_ADMIN'" label="角色">
        <template slot-scope="scope">
          {{ scope.row.roleName || "-" }}
        </template>
      </el-table-column>
      <el-table-column v-if="rolesCode === 'PLATFORM_ADMIN' || rolesCode === 'ROLE_ADMIN'" label="组织">
        <template slot-scope="scope">
          {{ scope.row.tenantName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="110">
        <template #header>
          <el-popover
            ref="statusPopover"
            placement="bottom"
            width="127"
            trigger="click"
            popper-class="custom-popover">
            <div slot="reference">
              <span class="search-title">状态</span>
              <i class="iconfont icon-biaogeshaixuan"></i>
            </div>
            <el-checkbox-group v-model="selectValue" class="status-group">
              <el-checkbox
                v-for="item in selectOptions"
                :key="item.value"
                :value="item.value"
                :label="item.value"
                class="status-checkbox">
                <div>{{ item.label }}</div>
              </el-checkbox>
            </el-checkbox-group>
            <div class="status-btn-box">
              <el-button size="mini" type="primary" class="btn" @click="filterStatus">确定</el-button>
            </div>
          </el-popover>
        </template>
        <template slot-scope="scope">
          <span class="identifying" :class="{ disable: scope.row.lockFlag === '9' }"></span>
          <span>{{ scope.row.lockFlag === '0' ? '正常' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template slot-scope="scope">
          <el-button type="text" size="operate" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="operate" @click="handleStatus(scope.row)">
            {{ scope.row.lockFlag === '0' ? '禁用' : '启用' }}
          </el-button>
          <el-button
            type="text"
            size="operate"
            :disabled="scope.row.lockFlag === '0'"
            @click="handleDelete(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>

    <el-dialog
      :title="status === 'add' ? '新增用户' : '编辑用户'"
      :visible.sync="dialogVisible"
      width="628px"
      :before-close="handleClose"
      custom-class="user-dialog">
      <el-form
        ref="form"
        class="define-form"
        :model="addFormData"
        :rules="rules"
        label-width="80px"
        label-position="right">
        <el-form-item label="账号" prop="username">
          <template #label>
            <span>账号</span>
            <el-tooltip content="支持邮箱" placement="top">
              <i class="iconfont icon-wenhao"></i>
            </el-tooltip>
          </template>
          <el-input
            v-model="addFormData.username"
            :disabled="status !== 'add'"
            placeholder="请输入邮箱"
            maxlength="32"
            clearable></el-input>
        </el-form-item>

        <el-form-item v-show="rolesCode === 'PLATFORM_ADMIN'" label="角色" prop="roleCode">
          <el-select v-model="addFormData.roleCode" placeholder="请选择角色" clearable>
            <el-option
              v-for="item in roleData"
              v-if="item.roleCode === 'CUSTOM_ADMIN'"
              :key="item.roleCode"
              :label="item.roleName"
              :value="item.roleCode"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-show="rolesCode !== 'PLATFORM_ADMIN'" label="角色" prop="roleCode">
          <el-select v-model="addFormData.roleCode" placeholder="请选择角色" clearable>
            <el-option
              v-for="item in roleData"
              :key="item.roleCode"
              :label="item.roleName"
              :value="item.roleCode"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-show="rolesCode === 'PLATFORM_ADMIN'" label="组织" prop="tenantId">
          <el-select v-model="addFormData.tenantId" placeholder="请选择组织" clearable>
            <el-option v-for="item in tenantData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="14" @click="onsubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addObj, delObj, putObj, lockFlag, getUserList } from '@/api/admin/user'
import { fetchList as tenantList } from '@/api/admin/tenant'
import { rolePage } from '@/api/admin/role'
import { mapGetters, mapState } from 'vuex'

export default {
  name: 'UserList',
  data() {
    return {
      searchName: '',
      tableUserData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: true,
      selectValue: [],
      selectOptions: [
        { value: 0, label: '正常' },
        { value: 9, label: '禁用' }
      ],
      dialogVisible: false,
      status: '', // 'add' or 'edit'
      addFormData: {
        userId: '',
        username: '',
        roleCode: '',
        tenantId: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: this.validateUserName, trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        tenantId: [
          { required: true, message: '请选择组织', trigger: 'change' }
        ]
      },
      tenantData: [],
      roleData: []
    }
  },
  computed: {
    ...mapGetters(['rolesCode']),
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  created() {
    this.queryUserList()
    setTimeout(() => this.querytenantList(), 100)
    this.queryRoleList()
  },
  methods: {
    // 获取初始表单数据
    getInitialFormData() {
      return {
        userId: '',
        username: '',
        roleCode: '',
        tenantId: ''
      }
    },
    // 验证用户名格式
    validateUserName(rule, value, callback) {
      const regex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (!regex.test(value)) {
        callback(new Error('请使用正确的邮箱作为账号'))
      } else {
        callback()
      }
    },
    // 查询用户列表
    queryUserList(condition) {
      if (condition === 'search') this.currentPage = 1
      this.loading = true
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        nameOrUsername: this.searchName,
        lockFlagList: this.selectValue
      }
      getUserList(params).then(res => {
        this.tableUserData = res.data.data.records
        this.total = res.data.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    // 查询角色列表
    queryRoleList() {
      rolePage().then(res => {
        this.roleData = res.data.data.records
      })
    },
    // 查询组织列表
    querytenantList() {
      tenantList().then(res => {
        this.tenantData = this.rolesCode === 'PLATFORM_ADMIN'
          ? res.data.data.filter(item => item.id !== '1')
          : res.data.data
      })
    },
    // 重置表单数据
    resetAddFormData(data = {}) {
      const base = this.getInitialFormData()
      Object.assign(this.addFormData, base, data)
    },
    // 新增用户
    handleAdd() {
      this.status = 'add'
      this.resetAddFormData()
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    // 编辑用户
    handleEdit(row) {
      this.status = 'edit'
      this.resetAddFormData(row)
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    // 删除用户
    handleDelete(id) {
      this.$confirm('删除后将导致该用户无法登录和使用，请谨慎操作。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(id).then(() => {
          this.$message.success('删除成功!')
          this.queryUserList()
        })
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.queryUserList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryUserList()
    },
    filterStatus() {
      this.queryUserList()
      this.$refs.statusPopover?.doClose()
    },
    // 提交表单
    onsubmit() {
      this.addFormData.tenantId = this.addFormData.tenantId || this.userInfo.tenantId
      this.$refs.form.validate(valid => {
        if (!valid) return false
        const apiCall = this.status === 'add' ? addObj : putObj
        apiCall({ ...this.addFormData }).then(() => {
          this.queryUserList()
          this.dialogVisible = false
        }).catch((error) => {
          this.$message.error(error.message)
        })
      })
    },
    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
      // 清空表单验证状态
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    handleStatus(row) {
      const params = {
        userId: row.userId,
        username: row.username,
        lockFlag: row.lockFlag === '0' ? '9' : '0'
      }
      lockFlag(params).then(() => {
        this.queryUserList()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.user-list {
  height: 100%;
  .title {
    font-size: 18px;
    font-weight: 600;
    color: #252525;
    margin-bottom: 21px;
  }
  .search-icon {
    cursor: pointer;
  }
  .button-container {
    float: right;
  }
}
.iconfont {
  margin-left: 2px;
  cursor: pointer;
}
.status-group {
  padding: 0 12px;
  .status-checkbox {
    display: block;
    height: 40px;
    line-height: 40px;
  }
}
.status-btn-box {
  text-align: center;
  border-top: 1px solid #E5E6E9;
  margin-top: 10px;
  .btn {
    margin-top: 10px;
  }
}
.identifying {
  width: 6px;
  height: 6px;
  display: inline-block;
  background: #1CBE49;
  border-radius: 50%;
  margin-right: 2px;
  margin-bottom: 1px;
}
.disable {
  background: #AEB0B9;
}
::v-deep .el-table__fixed-right-patch {
  background: #F5F6F7;
}
::v-deep .el-select {
  width: 100%;
}
::v-deep .el-input-group__append {
  background: transparent;
}
::v-deep .user-dialog .el-dialog__body {
  padding: 20px 80px !important;
}
</style>

<style>
.custom-popover {
  min-width: 127px !important;
  padding: 12px 0;
}
</style>
